package com.market.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Yun on 2016-01-08.
 */
public class CoreUtils {

    /**
     * 释放关闭资源
     * @param objs
     */
    public static void close(AutoCloseable... objs) {
        if(objs!=null){
            for (int i = 0; i < objs.length; i++) {
                if (objs[i] == null) {
                    continue;
                }
                try {
                    objs[i].close();
                } catch (Exception e) {
                    continue;
                }
            }
        }
    }

    /**
     * 异常信息
     * @param ex
     * @return
     */
    public static String trace(Exception ex) {
        StringWriter write = new StringWriter();
        ex.printStackTrace(new PrintWriter(write));
        String trace = write.toString();

        try {
            write.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            CoreUtils.close(write);
        }

        return trace;
    }

    /**
     * 对象转Map (只转有值属性)
     * @param obj
     * @return
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static Map convertToMap(Object obj) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        Map returnMap = new HashMap();
        if(obj!=null){
            Class type = obj.getClass();
            BeanInfo beanInfo = Introspector.getBeanInfo(type);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();
                if (!propertyName.equals("class")) {
                    Method readMethod = descriptor.getReadMethod();
                    Object result = readMethod.invoke(obj, new Object[0]);
                    if (result != null) {
                        returnMap.put(propertyName, result);
                    }
                }
            }
        }
        return returnMap;
    }
}
